/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    gongwenkai
 * 创建时间:    2023-09-27
 */
package org.jeecg.modules.flow.callback.outbound.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceipt;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceiptMaterial;
import org.jeecg.modules.business.doc.outbound.entity.vo.OutBoundReceiptSaveVO;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptMaterialService;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptService;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskPick;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskPickService;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.business.repertory.entity.vo.RepertoryDocumentVO;
import org.jeecg.modules.business.repertory.entity.vo.RepertoryVO;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.flow.callback.enums.DocumentStatusEnum;
import org.jeecg.modules.flow.callback.outbound.util.CommonOutboundUtil;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 销售出库出库单提交 回调bean(销售出库（定尺/铁心）使用)（已作废）
 *
 * @author gongwenkai
 * @version 1.0.0
 * @since 2023-09-27
 */
@Deprecated
@RequiredArgsConstructor
@Component
public class OutBoundReceiptXSCKSubmitBean<T> extends BaseCustomBeanRun<T> {

    private final IWmsOutReceiptService wmsOutReceiptService;

    private final IWmsOutReceiptMaterialService wmsOutReceiptMaterialService;

    private final IWmsRepertoryService wmsRepertoryService;

    private final IWmsOutReceiptTaskService wmsOutReceiptTaskService;

    private final CommonOutboundUtil commonOutboundUtil;

    /**
     * 业务逻辑 销售出库出库单提交
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        baseFlowDto.translateClass(JSONObject.class);
        JSONObject jsonVO = (JSONObject) baseFlowDto.getData();
        String receiptId = jsonVO.getString("id");
        String taskId;
        if (!StrUtil.isEmpty(receiptId)) {
            //有出库单id 说明出库单保存过
            WmsOutReceipt wmsOutReceipt = wmsOutReceiptService.getById(receiptId);
            if (Objects.isNull(wmsOutReceipt)) {
                throw new JeecgBootException("出库单不存在");
            }
            if (DocumentStatusEnum.CLOSE.getCode().equals(wmsOutReceipt.getDocumentStatus())) {
                throw new JeecgBootException("提交失败，所属出库任务已关闭");
            }
            taskId = wmsOutReceipt.getWmsOutReceiptTaskId();
            WmsOutReceiptTask wmsOutReceiptTask = wmsOutReceiptTaskService.getById(taskId);
            if (ObjectUtil.isNull(wmsOutReceiptTask)) {
                throw new JeecgBootException("出库任务不存在");
            }
            if (DocumentStatusEnum.CLOSE.getCode().equals(wmsOutReceiptTask.getDocumentStatus())) {
                throw new JeecgBootException("提交失败，所属出库任务已关闭");
            }
            if (jsonVO.getJSONArray("wmsOutReceiptMaterialList") != null) {
                WmsOutReceipt updateWmsOutReceipt = jsonVO.toJavaObject(WmsOutReceipt.class);
                List<WmsOutReceiptMaterial> updateOutReceiptMaterialList = jsonVO.getJSONArray("wmsOutReceiptMaterialList").toJavaList(WmsOutReceiptMaterial.class);
                wmsOutReceiptService.updateMain(updateWmsOutReceipt, updateOutReceiptMaterialList, false);
            }
            wmsOutReceiptService.update(new LambdaUpdateWrapper<WmsOutReceipt>()
                    .set(WmsOutReceipt::getDocumentStatus, DocumentStatusEnum.PROCESS.getCode())
                    .eq(WmsOutReceipt::getId, receiptId)
            );
            //校验即时库存
            wmsRepertoryService.outSubmit(receiptId, true);
            List<WmsOutReceiptMaterial> receiptMaterials = wmsOutReceiptMaterialService.list(new LambdaQueryWrapper<WmsOutReceiptMaterial>()
                    .eq(WmsOutReceiptMaterial::getWmsOutReceiptId, receiptId)
            );
            List<RepertoryVO> collect = receiptMaterials.stream().map(o -> {
                RepertoryVO repertoryVO = BeanUtil.copyProperties(o, RepertoryVO.class);
                repertoryVO.setStockQuantity(o.getOutboundQuantity());
                repertoryVO.setStockQuantitySub(o.getOutboundQuantityAssist());
                return repertoryVO;
            }).collect(Collectors.toList());
            RepertoryDocumentVO repertoryDocumentVO = new RepertoryDocumentVO();
            repertoryDocumentVO.setInvoicesId(receiptId);
            repertoryDocumentVO.setDocumentType(2);
            repertoryDocumentVO.setRepertoryVOS(collect);
            //扣除即时库存
            wmsRepertoryService.reduce(repertoryDocumentVO);
            //表单提交时，任务开始
            commonOutboundUtil.commonNoticeMesTaskStart(taskId, null);
            //更新任务状态
            //commonOutboundUtil.updateReceiptMaterial(wmsOutReceipt);
        } else {
            //没有出库单id 说明出库单直接提交
            OutBoundReceiptSaveVO saveVO = jsonVO.toJavaObject(OutBoundReceiptSaveVO.class);
            WmsOutReceipt wmsOutReceipt = new WmsOutReceipt();
            BeanUtils.copyProperties(saveVO, wmsOutReceipt);
            wmsOutReceipt.setId(null);
            receiptId = wmsOutReceiptService.saveMain(wmsOutReceipt, saveVO.getWmsOutReceiptMaterialList(), false);
            //更新单据状态
            wmsOutReceiptService.update(new LambdaUpdateWrapper<WmsOutReceipt>()
                    .set(WmsOutReceipt::getDocumentStatus, DocumentStatusEnum.PROCESS.getCode())
                    .eq(WmsOutReceipt::getId, receiptId)
            );

            //校验即时库存
            wmsRepertoryService.outSubmit(receiptId,true);
            List<WmsOutReceiptMaterial> receiptMaterials = saveVO.getWmsOutReceiptMaterialList();
            List<RepertoryVO> collect = receiptMaterials.stream().map(o -> {
                RepertoryVO repertoryVO = BeanUtil.copyProperties(o, RepertoryVO.class);
                repertoryVO.setStockQuantity(o.getOutboundQuantity());
                repertoryVO.setStockQuantitySub(o.getOutboundQuantityAssist());
                return repertoryVO;
            }).collect(Collectors.toList());
            RepertoryDocumentVO repertoryDocumentVO = new RepertoryDocumentVO();
            repertoryDocumentVO.setInvoicesId(receiptId);
            repertoryDocumentVO.setDocumentType(2);
            repertoryDocumentVO.setRepertoryVOS(collect);
            //扣除即时库存
            wmsRepertoryService.reduce(repertoryDocumentVO);
            taskId = wmsOutReceipt.getWmsOutReceiptTaskId();
            //表单提交时，任务开始
            commonOutboundUtil.commonNoticeMesTaskStart(taskId, null);
            //更新任务状态
            wmsOutReceipt.setId(receiptId);
            //commonOutboundUtil.updateReceiptMaterial(wmsOutReceipt);
        }
        // 当前前端调用业务需要你返回的
        baseFlowDto.setResult(Result.OK());
        // id是保存业务记录的id。用于生成业务流程信息记录
        baseFlowDto.setInfoId(receiptId);
    }

}
